package impexp.importfile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.aote.sql.SqlMapper;

public class JSONConfigAnaly implements IDataAnaly {

	private String jsonPath;

	public String getJsonPath() {
		return jsonPath;
	}

	public void setJsonPath(String jsonPath) {
		this.jsonPath = jsonPath;
	}

	@Override
	public JSONArray analy(List<String[]> data) {

		JSONArray result = new JSONArray();
		// 获取表头

		String[] headers = data.get(0);
		JSONArray template = JSONAnaly();
		for (int i = 1; i < data.size(); i++) {
			result.put(dealTools(headers, data.get(i), template));
		}
		System.out.println(result);
		return result;
	}

	private JSONObject dealTools(String[] headers, String[] datas,
			JSONArray jsonArr) {
		JSONObject result = new JSONObject();
		JSONObject temp = new JSONObject();
		for (int i = 0; i < headers.length; i++) {
			// 在json中在这个表头对应的字段

			String tablename = getKey(jsonArr, headers[i])[1];
			if (!result.has(tablename)) {
				temp = new JSONObject();
				result.put(tablename, temp);
			}
			result.put(tablename,
					temp.put(getKey(jsonArr, headers[i])[0], ("".equals(datas[i])) ? null:datas[i]));

		}
		return result;
	}

	/**

	 * 通过value获取key

	 * 

	 * @param arr

	 * @param value

	 * @return String[] 第一位：key 第二位：tablename

	 */
	private String[] getKey(JSONArray arr, String value) {
		String[] result = new String[2];
		boolean end = false;
		for (int j = 0; j < arr.length(); j++) {
			JSONObject obj = (JSONObject) arr.getJSONObject(j).get("data");
			Iterator<String> keys = obj.keys();
			while (keys.hasNext()) {
				String key = keys.next();
				if (value.trim().equals(obj.get(key).toString().trim())) {
					result[0] = key;
					result[1] = (String) arr.getJSONObject(j).get("tablename");
					end = true;
					break;
				}
			}
			if (end) {
				break;
			}
		}
		return result;
	}

	private JSONArray JSONAnaly() {

		BufferedReader reader = null;
		String laststr = "";

		try {
			InputStream input = SqlMapper.class.getClassLoader()
					.getResourceAsStream(jsonPath);
			InputStreamReader inputStreamReader = new InputStreamReader(input,
					"UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				laststr += tempString;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return new JSONArray(laststr);
	}

}